<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="4">
              <a-form-item label="员工名称">
                <a-select placeholder="请选择员工" v-model="queryParam.userId" :getPopupContainer="(triggerNode) => {
                    return triggerNode.parentNode || document.body;
                  }
                  " style="width: 100%" allow-clear>
                  <a-select-option v-for="d in userNamesList" :key="d.name" :value="d.id">{{ d.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="4">
              <a-form-item label="部门名称" prop="type">
                <a-tree-select v-model="queryParam.deptId" style="width: 100%"
                  :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="deptOptions"
                  placeholder="请选择部门" :replaceFields="{
                    children: 'children',
                    title: 'menuName',
                    key: 'id',
                    value: 'id',
                  }" @change="onMenuTreeChange" allow-clear>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="时间">
                <a-range-picker v-model="dateRange" valueFormat="YYYY-MM-DD" :show-today="true" />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item label="客户来源">
                <a-select placeholder="请选择来源" v-model="queryParam.laiyuan" style="width: 100%" allow-clear>
                  <a-select-option v-for="(d, index) in laiyuanOptions" :key="index" :value="d.dictValue">{{ d.dictLabel
                    }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col>
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="handleQuery"><a-icon type="search" />查询</a-button>
                <a-button style="margin-left: 8px" @click="resetQuery"><a-icon type="redo" />重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>

    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 数据统计横幅 -->
      <div class="data-view">
        <div class="view-item">
          <div class="item-title">
            <span>拨打数</span>
          </div>
          <div class="item-number">
            <span>1792</span>
          </div>
        </div>
        <div class="view-item">
          <div class="item-title">
            <span>拦截数</span>
          </div>
          <div class="item-number">
            <span>0</span>
          </div>
        </div>
        <div class="view-item">
          <div class="item-title">
            <span>拦截率</span>
          </div>
          <div class="item-number">
            <span>0.00%</span>
          </div>
        </div>
        <div class="view-item">
          <div class="item-title">
            <span>呼出数</span>
          </div>
          <div class="item-number">
            <span>1792</span>
          </div>
        </div>
        <div class="view-item">
          <div class="item-title">
            <span>呼出接听数</span>
          </div>
          <div class="item-number">
            <span>452</span>
          </div>
        </div>
        <div class="view-item">
          <div class="item-title">
            <span>未接通数</span>
          </div>
          <div class="item-number">
            <span>1340</span>
          </div>
        </div>
        <div class="view-item">
          <div class="item-title">
            <span>接听率</span>
          </div>
          <div class="item-number">
            <span>25.22%</span>
          </div>
        </div>
      </div>
      <!-- 数据统计echarts -->
      <div class="data-view-echarts">
        <div class="echarts-item" ref="echartsItem"></div>
      </div>
    </a-card>

    <a-card :bordered="false" class="table-card">
      <!-- 增加 -->
      <biz-cap-bill-add-form v-if="showAddModal" ref="bizCapBillAddForm" :typeOptions="typeOptions"
        :statusOptions="statusOptions" @ok="getList" @close="showAddModal = false" />
      <!-- 编辑 -->
      <biz-cap-bill-edit-form v-if="showEditModal" ref="bizCapBillEditForm" :typeOptions="typeOptions"
        :statusOptions="statusOptions" @ok="getList" @close="showEditModal = false" />
      <advance-table title="员工工作统计" :pagination="{
        current: queryParam.pageNum,
        pageSize: queryParam.pageSize,
        total: total,
        showSizeChanger: true,
        showLessItems: true,
        showQuickJumper: true,
        showTotal: (total, range) =>
          `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
        onChange: changeSize,
        onShowSizeChange: onShowSizeChange,
      }" tableKey="base-statistics-yingxiaotongji-table" rowKey="id" size="middle" @refresh="getList"
        :columns="columns" :data-source="bizDataList" :loading="loading" :format-conditions="true"
        :scroll="{ x: '100%' }">
        <!-- <div class="table-operations" slot="button">
          <a-button type="" @click="handleExport" v-hasPermi="['biz:bizCapBill:export']">
            <a-icon type="download" />导出
          </a-button>
        </div> -->
        <span slot="type" slot-scope="{ record }">
          {{ typeFormat(record) }}
        </span>

        <!-- <span slot="status" slot-scope="{ record }">
          {{ statusFormat(record) }}
        </span> -->
        <span slot="orgType" slot-scope="{ record }">
          {{ orgTypeFormat(record) }}
        </span>

        <span slot="status" slot-scope="{ record }">
          <a-tag color="orange" v-if="record.status == 0">
            {{ statusFormat(record) }}
          </a-tag>
          <a-tag color="green" v-if="record.status == 1">
            {{ statusFormat(record) }}
          </a-tag>
        </span>
        <span slot="numStr" slot-scope="{ text }">
          ¥ {{ formatNumber(text) }}
        </span>
        <span slot="amount" slot-scope="{ text }">
          ¥ {{ formatNumber(text) }}
          <!-- <span v-if="record.type"> / {{ typeFormat(record) }}</span> -->
        </span>
        <span slot="operation" slot-scope="{ text, record }">
          <a-button type="link" icon="transaction" @click="handleAdd(record)" v-if="record.status == 0">结算</a-button>
        </span>
        <span slot="rowindex" slot-scope="{ index }">
          {{ index + 1 }}
        </span>
        <span slot="jinjianId" slot-scope="{ text }">
          <a>{{ text }}</a>
        </span>
        <span slot="shangmenCountslv" slot-scope="{ record }">
          {{
            parseFloat(
              (record.shangmenCounts / record.yaoyueCounts || 0) * 100
            ).toFixed(2)
          }}%
        </span>
        <span slot="chengjiaoCountslv" slot-scope="{ record }">
          {{
            parseFloat(
              (record.chengjiaoCounts / record.jinxianCounts || 0) * 100
            ).toFixed(2)
          }}%
        </span>
        <span slot="youzhiCountslv" slot-scope="{ record }">
          {{
            parseFloat(
              (record.youzhiCounts / record.jinxianCounts || 0) * 100
            ).toFixed(2)
          }}%
        </span>
        <span slot="counts" slot-scope="{ text }">
          {{ text || 0 }}
        </span>
        <span slot="fkAmounts" slot-scope="{ text }">
          ¥ {{ parseFloat(text || 0).toFixed(2) }}
        </span>
        <span slot="zhunRuCounts" slot-scope="{ text, record }">
          {{ text || 0 }}/{{
            text == 0 || record.newCustomers == 0
              ? parseFloat(0).toFixed(2)
              : parseFloat(
                ((text || 0) / (record.newCustomers || 0)) * 100
              ).toFixed(2)
          }}%
        </span>
        <span slot="tohomeCounts" slot-scope="{ text }">
          {{ text || 0 }}
        </span>
      </advance-table>
    </a-card>
  </div>
</template>
<script>
import * as echarts from "echarts"
import { listBizProductInfo } from "@/api/biz/bizProductInfo";

import AdvanceTable from "@/components/pt/table/AdvanceTable";
import BizCapBillAddForm from "@/views/biz/capbill/modules/BizCapBillAddForm";
import BizCapBillEditForm from "@/views/biz/capbill/modules/BizCapBillEditForm";
import {
  listUser,
  statisticsUserByLaiyuan,
  exportstatisticsUserByLaiyuan,
} from "@/api/system/user";
import { listDeptTree } from "@/api/system/dept";
export default {
  name: "BizCapBill",
  components: {
    AdvanceTable,
    BizCapBillAddForm,
    BizCapBillEditForm,
  },
  data() {
    return {
      showAddModal: false,
      showEditModal: false,
      // echarts相关
      echartsItem: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 资方结算表格数据
      bizDataList: [],
      orgTypeOptions: [],
      // 结算类型字典
      typeOptions: [],
      // 结算状态字典
      statusOptions: [],
      dateRange: [],
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        userName: undefined,

        deptName: undefined,

        jinjianId: undefined,

        cusName: undefined,

        beginQdTime: undefined,

        status: undefined,
      },

      columns: [
        // {
        //   title: "序号",
        //   dataIndex: "rowindex",
        //   ellipsis: true,
        //   align: "center",
        //   width: "60px",
        //   scopedSlots: { customRender: "rowindex" },
        // },
        {
          title: "员工名称",
          dataIndex: "newCustomers",
          ellipsis: true,
          align: "right",
          width: "120px",
        },
        {
          title: "部门名称",
          dataIndex: "name",
          align: "right",
          width: "100px",
        },
        {
          title: "拨打数",
          dataIndex: "zhunRuCounts",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "zhunRuCounts" },
        },
        {
          title: "拦截数",
          dataIndex: "tohomeCounts",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "tohomeCounts" },
        },
        {
          title: "拦截率",
          dataIndex: "cjCounts",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "cjCounts" },
        },
        {
          title: "呼出数",
          dataIndex: "fkCounts",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "fkCounts" },
        },
        {
          title: "呼出接听数",
          dataIndex: "fkAmounts",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "fkAmounts" },
        },
        {
          title: "未接通数",
          dataIndex: "fkAmounts2",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "fkAmounts2" },
        },
        {
          title: "通话总时长",
          dataIndex: "fkAmounts3",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "fkAmounts3" },
        },
        {
          title: "接听率",
          dataIndex: "fkAmounts4",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "fkAmounts4" },
        },
        {
          title: "呼出客户数",
          dataIndex: "fkAmounts5",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "fkAmounts5" },
        },
        {
          title: "接听客户数",
          dataIndex: "fkAmounts6",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "fkAmounts6" },
        },
        {
          title: "客户接听率",
          dataIndex: "fkAmounts7",
          ellipsis: true,
          align: "right",
          width: "120px",
          scopedSlots: { customRender: "fkAmounts7" },
        },
      ],
      laiyuanOptions: [],
      // 根据岗位删选员工
      postIds: ["gwzg", "rzgw", "qyjl", "sg"],
      // 部门信息
      deptOptions: [],
      userNamesList: [],
      isKefu: 2,
    };
  },
  created() {
    this.setInfo()
    this.getList();
    this.getDicts("zifang_jiesuan_type").then((response) => {
      this.typeOptions = response.data;
    });
    this.getDicts("zifang_jiesuan_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("org_type_options").then((response) => {
      this.orgTypeOptions = response.data;
    });
    this.getDicts("bus_type").then((response) => {
      this.laiyuanOptions = response.data;
    });
    this.getDeptList();
  },
  methods: {
    setInfo() {
      setTimeout(() => {
        this.setData()
      }, 1000);
    },
    setData() {
      this.echartsItem = echarts.init(this.$refs.echartsItem)
      // let keyData = this.data.keyData;
      // let valueData = this.data.valueData;
      var option
      const colors = ["#00C7FA","#D76FE2","#20D7C5","#4C93FF","#FFCB81","#FF7F65","#7272FF"];
      option = {
        color: colors,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross"
          },
          formatter: function (params) {
            let result = params[0].name + "<br>";
            params.forEach(function (item) {
              if (item.seriesType === "bar") {
                result += item.marker + " " + item.seriesName + ": " + item.value + "个<br>";
              } else if (item.seriesType === "line") {
                result += item.marker + " " + item.seriesName + ": " + item.value + "%<br>";
              }
            });
            return result;
          }
        },
        grid: {
          left: "6%",
          right: "6%",
          bottom: "10%",
          containLabel: true
        },
        toolbox: {
          feature: {
            // dataView: { show: true, readOnly: false },
            // restore: { show: true },
            saveAsImage: { show: true }
          }
        },
        legend: {
          data: ["拨打数", "拦截数", "拦截率", "呼出数", "呼出接听数", "未接通数", "接听率"]
        },
        xAxis: [
          {
            type: "category",
            axisTick: {
              alignWithLabel: true
            },
            data: ["2025-08-01", "2025-08-02", "2025-08-03", "2025-08-04"]
          }
        ],
        yAxis: [
          {
            type: "value",
            name: "呼出数/呼出接听数",
            position: "left",
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#333"
              }
            },
            axisLabel: {
              formatter: "{value}个"
            }
          },
          {
            type: "value",
            name: "拦截率/接听率",
            position: "right",
            alignTicks: true,
            axisLine: {
              show: true,
              lineStyle: {
                color: "#333"
              }
            },
            axisLabel: {
              formatter: "{value}%"
            },
            max: 100 // 设置最大值为 100%
          }
        ],
        series: [
          {
            name: "拨打数",
            type: "bar",
            barWidth:"6%",
            data: [268,491, 701, 232]
          },
          {
            name: "拦截数",
            type: "bar",
            barWidth:"6%",
            data: [12, 10, 20, 26]
          },
          {
            name: "拦截率",
            type: "line",
            yAxisIndex: 1, // 使用右边的 yAxis
            data: [10, 20, 30, 10]
          },
          {
            name: "呼出数",
            type: "bar",
            barWidth:"6%",
            data: [1802, 2410, 2320, 1626]
          },
          {
            name: "呼出接听数",
            type: "bar",
            barWidth:"6%",
            data: [1792, 992, 1120, 892]
          },
          {
            name: "未接通数",
            type: "bar",
            barWidth:"6%",
            data: [1220, 1100, 980, 1340]
          },
          {
            name: "接听率",
            type: "line",
            yAxisIndex: 1, // 使用右边的 yAxis
            data: [100, 0, 0, 100]
          },
        ]
      };
      this.echartsItem.setOption(option)
    },
    getUserList(deptId) {
      const params = {
        pageNum: 1,
        pageSize: 100,
        deptId: deptId,
      };
      if (this.isKefu) {
        params.isKefu = this.isKefu;
      }
      if (this.postIds) {
        params.postIds = this.postIds;
      }
      listUser(params).then((res) => {
        this.userNamesList = res.data.list;
      });
    },
    onMenuTreeChange(value) {
      this.getUserList(value);
    },
    getDeptList() {
      listDeptTree("", 3).then((response) => {
        // this.expandTree(response.data, 3, this.expandedRowKeys);
        this.deptOptions = response.data;
      });
    },
    handleChooseProduct(val, options) {
      // this.form.productId = val;
      // this.form.productName = options.key;
    },
    handleGetProductInfo(value) {
      listBizProductInfo({ orgType: value, pageSize: 50 }).then((res) => {
        this.productList = res.data.list;
      });
    },
    formatNumber(num) {
      return parseFloat(num || 0).toFixed(2);
    },
    /** 查询资方结算列表 */
    getList() {
      this.loading = true;
      statisticsUserByLaiyuan(
        this.addDateRange(this.queryParam, this.dateRange)
      ).then((res) => {
        this.bizDataList = res.data.list;
        this.total = res.data.total;
        this.loading = false;
      });
    },
    // 结算类型字典翻译
    typeFormat(row) {
      if (row.type) {
        return this.selectDictLabel(this.typeOptions, row.type);
      } else {
        return "";
      }
    },
    // 结算类型字典翻译
    orgTypeFormat(row) {
      if (row.orgType) {
        return this.selectDictLabel(this.orgTypeOptions, row.orgType);
      } else {
        return "";
      }
    },
    // 结算状态字典翻译
    statusFormat(row) {
      if (row.status) {
        return this.selectDictLabel(this.statusOptions, row.status);
      } else {
        return "";
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        userName: undefined,

        deptName: undefined,

        jinjianId: undefined,

        cusName: undefined,

        beginQdTime: undefined,

        status: undefined,
      };
      this.handleQuery();
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList();
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleAdd(record) {
      if (record.status === "1") {
        this.$message.warning("请勿重复结算", 3);
        return;
      }
      this.showAddModal = true;
      this.$nextTick(() => this.$refs.bizCapBillAddForm.handleAdd(record));
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.bizCapBillEditForm.handleUpdate(record, ids)
      );
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportstatisticsUserByLaiyuan(that.queryParam).then(
            (response) => {
              that.download(response.msg);
              that.$message.success("导出成功", 3);
            }
          );
        },
        onCancel() { },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.data-view {
  display: flex;
  flex-wrap: wrap;
  padding: 20px 0;
  width: 70%;
  margin: 20px auto;
  border: 1px solid #93b8e6;
  border-radius: 5px;
}

.view-item {
  width: 14.28%;
  text-align: center;
  border-right: 1px solid #93b8e6;
}

.view-item:last-child {
  border-right: none;
}

.item-title {
  font-size: 14px;
  color: #636363;
}

.item-number {
  font-size: 18px;
  font-weight: bold;
  margin-top: 5px;
}

.data-view-echarts{
  width: 100%;
  margin-top: 10px;
}

.echarts-item{
  width: 100%;
  height: 400px;
  margin: 0 auto;
}
</style>
